{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "77123bae-0932-48ba-8726-19279eab0ce1",
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "from openai import OpenAI\n",
    "\n",
    "# 建议将 API Key 设置为环境变量，避免直接暴露在代码中\n",
    "# 从环境变量获取 DeepSeek API Key\n",
    "api_key = os.getenv(\"DEEPSEEK_API_KEY\")\n",
    "if not api_key:\n",
    "    raise ValueError(\"请设置 DEEPSEEK_API_KEY 环境变量\")\n",
    "\n",
    "# 初始化 DeepSeek 客户端\n",
    "\n",
    "client = OpenAI(\n",
    "    api_key=api_key,\n",
    "    base_url=\"https://api.deepseek.com/v1\",  # DeepSeek API 的基地址\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "eb66fbf4-2fda-4d0b-bb48-b9a48aff10dc",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "['智能手表：参数是1.5英寸AMOLED环形屏，钛合金机身，双芯架构，30米防水，优点：全球首款医疗级AI健康预警系统，通过FDA二类认证磁吸式快充技术实现15分钟充至80%，卖点：数字孪生表盘与元宇宙形象实时联动，碳中和设计：采用100%再生稀土电机。', '笔记本电脑：参数是14.2英寸QLED可变刷新率屏，碳纤维铰链结构，骁龙X Elite处理器，全机仅789g，优点：全球最轻的16GB内存笔记本，无风扇设计，卖点：全息投影键盘支持触觉反馈的空中输入，生物识别安全舱支持掌静脉+视网膜双认证，', '平板电脑：参数是11英寸柔性OLED，纳米纹理防眩涂层，天玑9300芯片，磁吸式模块化配件接口，优点：首款支持触觉模拟的屏幕，模块化设计可外接电子墨水屏或全键盘', '手机：参数是6.7英寸动态棱镜屏，液态金属中框，200MP量子点主摄，自修复纳米疏油层，优点：首款通过TUV认证的蓝光护眼屏,石墨烯电池循环2000次,卖点：利用光子晶体实现裸眼3D视频，背部光伏膜日均补充8%电量']\n",
      "4\n"
     ]
    }
   ],
   "source": [
    "from glob import glob\n",
    "\n",
    "text_lines = []\n",
    "\n",
    "for file_path in glob(\"ep.md\", recursive=True):\n",
    "    with open(file_path, \"r\") as file:\n",
    "        file_text = file.read()\n",
    "\n",
    "    text_lines += file_text.split(\"\\n\")\n",
    "print(text_lines)\n",
    "print(len(text_lines))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "ec635c6b-60be-489c-ae38-30cbf849fb89",
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/root/miniconda3/envs/deepseek/lib/python3.13/site-packages/tqdm/auto.py:21: TqdmWarning: IProgress not found. Please update jupyter and ipywidgets. See https://ipywidgets.readthedocs.io/en/stable/user_install.html\n",
      "  from .autonotebook import tqdm as notebook_tqdm\n"
     ]
    }
   ],
   "source": [
    "from pymilvus import model as milvus_model\n",
    "\n",
    "embedding_model = milvus_model.DefaultEmbeddingFunction()\n",
    "\n",
    "test_embedding = embedding_model.encode_queries([\"This is a test\"])[0]\n",
    "embedding_dim = len(test_embedding)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "c3f6f8f7-efe0-442c-89d8-c32e55b9687e",
   "metadata": {},
   "outputs": [],
   "source": [
    "from pymilvus import MilvusClient\n",
    "\n",
    "milvus_client = MilvusClient(uri=\"./milvus_ep.db\")\n",
    "\n",
    "collection_name = \"my_rag_collection\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "fc30e7ef-4dbc-4978-9896-9924b0316159",
   "metadata": {},
   "outputs": [],
   "source": [
    "if milvus_client.has_collection(collection_name):\n",
    "    milvus_client.drop_collection(collection_name)\n",
    "\n",
    "milvus_client.create_collection(\n",
    "    collection_name=collection_name,\n",
    "    dimension=embedding_dim,\n",
    "    metric_type=\"IP\",  # 内积距离\n",
    "    consistency_level=\"Strong\",  # 支持的值为 (`\"Strong\"`, `\"Session\"`, `\"Bounded\"`, `\"Eventually\"`)。更多详情请参见 https://milvus.io/docs/consistency.md#Consistency-Level。\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "e9531b0d-0810-4b59-9433-cbde1f80944f",
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Creating embeddings: 100%|██████████| 4/4 [00:00<00:00, 7247.18it/s]\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "{'insert_count': 4, 'ids': [0, 1, 2, 3], 'cost': 0}"
      ]
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from tqdm import tqdm\n",
    "\n",
    "data = []\n",
    "\n",
    "doc_embeddings = embedding_model.encode_documents(text_lines)\n",
    "for i, line in enumerate(tqdm(text_lines, desc=\"Creating embeddings\")):\n",
    "    data.append({\"id\": i, \"vector\": doc_embeddings[i], \"text\": line})\n",
    "\n",
    "milvus_client.insert(collection_name=collection_name, data=data)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "dc5b4d45-35ce-4211-9dfb-00b77be246f3",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "平板电脑：参数是11英寸柔性OLED，纳米纹理防眩涂层，天玑9300芯片，磁吸式模块化配件接口，优点：首款支持触觉模拟的屏幕，模块化设计可外接电子墨水屏或全键盘\n",
      "智能手表：参数是1.5英寸AMOLED环形屏，钛合金机身，双芯架构，30米防水，优点：全球首款医疗级AI健康预警系统，通过FDA二类认证磁吸式快充技术实现15分钟充至80%，卖点：数字孪生表盘与元宇宙形象实时联动，碳中和设计：采用100%再生稀土电机。\n",
      "笔记本电脑：参数是14.2英寸QLED可变刷新率屏，碳纤维铰链结构，骁龙X Elite处理器，全机仅789g，优点：全球最轻的16GB内存笔记本，无风扇设计，卖点：全息投影键盘支持触觉反馈的空中输入，生物识别安全舱支持掌静脉+视网膜双认证，\n",
      "以下是智能手表的详细答案，基于提供的参数和卖点整理：\n",
      "\n",
      "**智能手表**  \n",
      "- **屏幕参数**：1.5英寸AMOLED环形屏  \n",
      "- **机身材质**：钛合金（轻量高强）  \n",
      "- **硬件配置**：双芯架构（高性能+低功耗协同）  \n",
      "- **防水等级**：30米防水（适合游泳等日常防水场景）  \n",
      "\n",
      "**核心优点**：  \n",
      "1. **医疗级健康监测**：  \n",
      "   - 全球首款搭载AI健康预警系统，可实时分析心率、血氧、血压等数据，并提供异常预警。  \n",
      "   - 通过**FDA二类认证**，确保医疗级数据可靠性。  \n",
      "2. **快充技术**：磁吸式快充，15分钟即可充至80%电量。  \n",
      "\n",
      "**创新卖点**：  \n",
      "- **元宇宙联动**：数字孪生表盘可同步用户元宇宙虚拟形象，实时交互（如表情、动作反馈）。  \n",
      "- **环保设计**：采用100%再生稀土电机，符合碳中和理念。  \n",
      "\n",
      "**适用场景**：  \n",
      "- 健康管理（尤其适合需长期监测的慢性病患者）  \n",
      "- 科技爱好者（元宇宙交互、未来感设计）  \n",
      "- 商务/户外用户（钛合金耐用性+快充便利性）  \n",
      "\n",
      "若有其他需强调的细节（如具体健康功能或价格），可进一步补充。\n"
     ]
    }
   ],
   "source": [
    "product_name=\"智能手表\"\n",
    "search_res = milvus_client.search(\n",
    "    collection_name=collection_name,\n",
    "    data=embedding_model.encode_queries(\n",
    "        [product_name]\n",
    "    ),  # 将问题转换为嵌入向量\n",
    "    limit=3,  # 返回前3个结果\n",
    "    search_params={\"metric_type\": \"IP\", \"params\": {}},  # 内积距离\n",
    "    output_fields=[\"text\"],  # 返回 text 字段\n",
    ")\n",
    "\n",
    "retrieved_lines_with_distances = [\n",
    "    (res[\"entity\"][\"text\"], res[\"distance\"]) for res in search_res[0]\n",
    "]\n",
    "\n",
    "context = \"\\n\".join(\n",
    "    [line_with_distance[0] for line_with_distance in retrieved_lines_with_distances]\n",
    ")\n",
    "\n",
    "print(context)\n",
    "print(query_ai(product_name,context))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "0f65ea55-d0b3-4a1c-8b5f-fd435a4c271f",
   "metadata": {},
   "outputs": [],
   "source": [
    "SYSTEM_PROMPT = \"\"\"\n",
    "你是一个资深的小红书爆款文案专家，擅长结合最新潮流和产品卖点，创作引人入胜、高互动、高转化的笔记文案。\n",
    "\n",
    "你的任务是根据用户提供的产品和需求，生成包含标题、正文、相关标签和表情符号的完整小红书笔记。\n",
    "\n",
    "请始终采用'Thought-Action-Observation'模式进行推理和行动。文案风格需活泼、真诚、富有感染力。当完成任务后，请以JSON格式直接输出最终文案，格式如下：\n",
    "```json\n",
    "{\n",
    "  \"title\": \"小红书标题\",\n",
    "  \"body\": \"小红书正文\",\n",
    "  \"hashtags\": [\"#标签1\", \"#标签2\", \"#标签3\", \"#标签4\", \"#标签5\"],\n",
    "  \"emojis\": [\"✨\", \"🔥\", \"💖\"]\n",
    "}\n",
    "```\n",
    "在生成文案前，请务必先思考并收集足够的信息。\n",
    "\"\"\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "96d63ca8-d5f7-48ce-b161-7449bc951297",
   "metadata": {},
   "outputs": [],
   "source": [
    "TOOLS_DEFINITION = [\n",
    "    {\n",
    "        \"type\": \"function\",\n",
    "        \"function\": {\n",
    "            \"name\": \"search_web\",\n",
    "            \"description\": \"搜索互联网上的实时信息，用于获取最新新闻、流行趋势、用户评价、行业报告等。请确保搜索关键词精确，避免宽泛的查询。\",\n",
    "            \"parameters\": {\n",
    "                \"type\": \"object\",\n",
    "                \"properties\": {\n",
    "                    \"query\": {\n",
    "                        \"type\": \"string\",\n",
    "                        \"description\": \"要搜索的关键词或问题，例如'最新小红书美妆趋势'或'深海蓝藻保湿面膜 用户评价'\"\n",
    "                    }\n",
    "                },\n",
    "                \"required\": [\"query\"]\n",
    "            }\n",
    "        }\n",
    "    },\n",
    "    {\n",
    "        \"type\": \"function\",\n",
    "        \"function\": {\n",
    "            \"name\": \"query_product_database\",\n",
    "            \"description\": \"查询内部产品数据库，获取指定产品的详细卖点、成分、适用人群、使用方法等信息。\",\n",
    "            \"parameters\": {\n",
    "                \"type\": \"object\",\n",
    "                \"properties\": {\n",
    "                    \"product_name\": {\n",
    "                        \"type\": \"string\",\n",
    "                        \"description\": \"要查询的产品名称，例如'深海蓝藻保湿面膜'\"\n",
    "                    }\n",
    "                },\n",
    "                \"required\": [\"product_name\"]\n",
    "            }\n",
    "        }\n",
    "    },\n",
    "    {\n",
    "        \"type\": \"function\",\n",
    "        \"function\": {\n",
    "            \"name\": \"generate_emoji\",\n",
    "            \"description\": \"根据提供的文本内容，生成一组适合小红书风格的表情符号。\",\n",
    "            \"parameters\": {\n",
    "                \"type\": \"object\",\n",
    "                \"properties\": {\n",
    "                    \"context\": {\n",
    "                        \"type\": \"string\",\n",
    "                        \"description\": \"文案的关键内容或情感，例如'惊喜效果'、'补水保湿'\"\n",
    "                    }\n",
    "                },\n",
    "                \"required\": [\"context\"]\n",
    "            }\n",
    "        }\n",
    "    }\n",
    "]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "ef46e551-66f5-45c2-a1b7-c3777f41e816",
   "metadata": {},
   "outputs": [],
   "source": [
    "TOOLS_DEFINITION = [\n",
    "    {\n",
    "        \"type\": \"function\",\n",
    "        \"function\": {\n",
    "            \"name\": \"query_product_database\",\n",
    "            \"description\": \"查询内部产品数据库，获取指定产品的详细卖点、成分、适用人群、使用方法等信息。\",\n",
    "            \"parameters\": {\n",
    "                \"type\": \"object\",\n",
    "                \"properties\": {\n",
    "                    \"product_name\": {\n",
    "                        \"type\": \"string\",\n",
    "                        \"description\": \"要查询的产品名称，例如'深海蓝藻保湿面膜'\"\n",
    "                    }\n",
    "                },\n",
    "                \"required\": [\"product_name\"]\n",
    "            }\n",
    "        }\n",
    "    }\n",
    "]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "28da35c1-31c0-4053-8cad-e3f7319ee0eb",
   "metadata": {},
   "outputs": [],
   "source": [
    "def query_ai(product_name : str, context : str) -> str:\n",
    "    response = client.chat.completions.create(\n",
    "        model=\"deepseek-chat\",\n",
    "        messages=[\n",
    "            {\"role\": \"system\", \"content\": \"你是一个 AI 助手。你能够从提供的上下文段落片段中找到问题的答案。\"},\n",
    "            {\"role\": \"user\", \"content\": f\"根据提供的{context}，返回{product_name}的答案\"},\n",
    "        ],\n",
    "    )\n",
    "    return response.choices[0].message.content"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "cd99df78-6e0e-4eae-8263-af2efd5dc40c",
   "metadata": {},
   "outputs": [],
   "source": [
    "import random # 用于模拟生成表情\n",
    "import time # 用于模拟网络延迟\n",
    "\n",
    "def mock_search_web(query: str) -> str:\n",
    "    \"\"\"模拟网页搜索工具，返回预设的搜索结果。\"\"\"\n",
    "    print(f\"[Tool Call] 模拟搜索网页：{query}\")\n",
    "    time.sleep(1) # 模拟网络延迟\n",
    "    if \"小红书美妆趋势\" in query:\n",
    "        return \"近期小红书美妆流行'多巴胺穿搭'、'早C晚A'护肤理念、'伪素颜'妆容，热门关键词有#氛围感、#抗老、#屏障修复。\"\n",
    "    elif \"保湿面膜\" in query:\n",
    "        return \"小红书保湿面膜热门话题：沙漠干皮救星、熬夜急救面膜、水光肌养成。用户痛点：卡粉、泛红、紧绷感。\"\n",
    "    elif \"深海蓝藻保湿面膜\" in query:\n",
    "        return \"关于深海蓝藻保湿面膜的用户评价：普遍反馈补水效果好，吸收快，对敏感肌友好。有用户提到价格略高，但效果值得。\"\n",
    "    else:\n",
    "        return f\"未找到关于 '{query}' 的特定信息，但市场反馈通常关注产品成分、功效和用户体验。\"\n",
    "\n",
    "def mock_query_product_database(product_name: str) -> str:\n",
    "    \"\"\"模拟查询产品数据库，返回预设的产品信息。\"\"\"\n",
    "    print(f\"[Tool Call] 模拟查询产品数据库：{product_name}\")\n",
    "    search_res = milvus_client.search(\n",
    "        collection_name=collection_name,\n",
    "        data=embedding_model.encode_queries(\n",
    "            [product_name]\n",
    "        ),  # 将问题转换为嵌入向量\n",
    "        limit=3,  # 返回前3个结果\n",
    "        search_params={\"metric_type\": \"IP\", \"params\": {}},  # 内积距离\n",
    "        output_fields=[\"text\"],  # 返回 text 字段\n",
    "    )\n",
    "\n",
    "    retrieved_lines_with_distances = [\n",
    "        (res[\"entity\"][\"text\"], res[\"distance\"]) for res in search_res[0]\n",
    "    ]\n",
    "\n",
    "    context = \"\\n\".join(\n",
    "        [line_with_distance[0] for line_with_distance in retrieved_lines_with_distances]\n",
    "    )\n",
    "    \n",
    "    if context:\n",
    "        return query_ai(product_name,context)\n",
    "    else:\n",
    "        return f\"产品数据库中未找到关于'{product_name}'的详细信息。\"\n",
    "\n",
    "def mock_generate_emoji(context: str) -> list:\n",
    "    \"\"\"模拟生成表情符号，根据上下文提供常用表情。\"\"\"\n",
    "    print(f\"[Tool Call] 模拟生成表情符号，上下文：{context}\")\n",
    "    time.sleep(0.2) # 模拟生成延迟\n",
    "    if \"补水\" in context or \"水润\" in context or \"保湿\" in context:\n",
    "        return [\"💦\", \"💧\", \"🌊\", \"✨\"]\n",
    "    elif \"惊喜\" in context or \"哇塞\" in context or \"爱了\" in context:\n",
    "        return [\"💖\", \"😍\", \"🤩\", \"💯\"]\n",
    "    elif \"熬夜\" in context or \"疲惫\" in context:\n",
    "        return [\"😭\", \"😮‍💨\", \"😴\", \"💡\"]\n",
    "    elif \"好物\" in context or \"推荐\" in context:\n",
    "        return [\"✅\", \"👍\", \"⭐\", \"🛍️\"]\n",
    "    else:\n",
    "        return random.sample([\"✨\", \"🔥\", \"💖\", \"💯\", \"🎉\", \"👍\", \"🤩\", \"💧\", \"🌿\"], k=min(5, len(context.split())))\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "f0f18af5-4366-4ff1-aff5-5a0a3f9ce347",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 将模拟工具函数映射到一个字典，方便通过名称调用\n",
    "available_tools = {\n",
    "    \"search_web\": mock_search_web,\n",
    "    \"query_product_database\": mock_query_product_database,\n",
    "    \"generate_emoji\": mock_generate_emoji,\n",
    "}"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "af107cd7-9a7e-42a2-a227-9f590e3242e5",
   "metadata": {},
   "outputs": [],
   "source": [
    "import json\n",
    "import re\n",
    "\n",
    "def generate_rednote(product_name: str, tone_style: str = \"活泼甜美\", max_iterations: int = 3) -> str:\n",
    "    \"\"\"\n",
    "    使用 DeepSeek Agent 生成小红书爆款文案。\n",
    "    \n",
    "    Args:\n",
    "        product_name (str): 要生成文案的产品名称。\n",
    "        tone_style (str): 文案的语气和风格，如\"活泼甜美\"、\"知性\"、\"搞怪\"等。\n",
    "        max_iterations (int): Agent 最大迭代次数，防止无限循环。\n",
    "        \n",
    "    Returns:\n",
    "        str: 生成的爆款文案（JSON 格式字符串）。\n",
    "    \"\"\"\n",
    "    \n",
    "    print(f\"\\n🚀 启动小红书文案生成助手，产品：{product_name}，风格：{tone_style}\\n\")\n",
    "    \n",
    "    # 存储对话历史，包括系统提示词和用户请求\n",
    "    messages = [\n",
    "        {\"role\": \"system\", \"content\": SYSTEM_PROMPT},\n",
    "        {\"role\": \"user\", \"content\": f\"请为产品「{product_name}」生成一篇小红书爆款文案。要求：语气{tone_style}，包含标题、正文、至少5个相关标签和5个表情符号。请以完整的JSON格式输出，并确保JSON内容用markdown代码块包裹（例如：```json{{...}}```）。\"}\n",
    "    ]\n",
    "    \n",
    "    iteration_count = 0\n",
    "    final_response = None\n",
    "    \n",
    "    while iteration_count < max_iterations:\n",
    "        iteration_count += 1\n",
    "        print(f\"-- Iteration {iteration_count} --\")\n",
    "        \n",
    "        try:\n",
    "            # 调用 DeepSeek API，传入对话历史和工具定义\n",
    "            response = client.chat.completions.create(\n",
    "                model=\"deepseek-chat\",\n",
    "                messages=messages,\n",
    "                tools=TOOLS_DEFINITION, # 告知模型可用的工具\n",
    "                tool_choice=\"auto\"  #requied 强制使用工具（不指定具体是哪个） {\"type\": \"function\", \"function\": {\"name\": \"mock_query_product_database\"}}\n",
    "            )\n",
    "\n",
    "            response_message = response.choices[0].message\n",
    "            \n",
    "            # **ReAct模式：处理工具调用**\n",
    "            if response_message.tool_calls: # 如果模型决定调用工具\n",
    "                print(\"Agent: 决定调用工具...\")\n",
    "                messages.append(response_message) # 将工具调用信息添加到对话历史\n",
    "                \n",
    "                tool_outputs = []\n",
    "                for tool_call in response_message.tool_calls:\n",
    "                    function_name = tool_call.function.name\n",
    "                    # 确保参数是合法的JSON字符串，即使工具不要求参数，也需要传递空字典\n",
    "                    function_args = json.loads(tool_call.function.arguments) if tool_call.function.arguments else {}\n",
    "\n",
    "                    print(f\"Agent Action: 调用工具 '{function_name}'，参数：{function_args}\")\n",
    "                    \n",
    "                    # 查找并执行对应的模拟工具函数\n",
    "                    if function_name in available_tools:\n",
    "                        tool_function = available_tools[function_name]\n",
    "                        tool_result = tool_function(**function_args)\n",
    "                        print(f\"Observation: 工具返回结果：{tool_result}\")\n",
    "                        tool_outputs.append({\n",
    "                            \"tool_call_id\": tool_call.id,\n",
    "                            \"role\": \"tool\",\n",
    "                            \"content\": str(tool_result) # 工具结果作为字符串返回\n",
    "                        })\n",
    "                    else:\n",
    "                        error_message = f\"错误：未知的工具 '{function_name}'\"\n",
    "                        print(error_message)\n",
    "                        tool_outputs.append({\n",
    "                            \"tool_call_id\": tool_call.id,\n",
    "                            \"role\": \"tool\",\n",
    "                            \"content\": error_message\n",
    "                        })\n",
    "                messages.extend(tool_outputs) # 将工具执行结果作为 Observation 添加到对话历史\n",
    "                \n",
    "            # **ReAct 模式：处理最终内容**\n",
    "            elif response_message.content: # 如果模型直接返回内容（通常是最终答案）\n",
    "                print(f\"[模型生成结果] {response_message.content}\")\n",
    "                \n",
    "                # --- START: 添加 JSON 提取和解析逻辑 ---\n",
    "                json_string_match = re.search(r\"```json\\s*(\\{.*\\})\\s*```\", response_message.content, re.DOTALL)\n",
    "                \n",
    "                if json_string_match:\n",
    "                    extracted_json_content = json_string_match.group(1)\n",
    "                    try:\n",
    "                        final_response = json.loads(extracted_json_content)\n",
    "                        print(\"Agent: 任务完成，成功解析最终JSON文案。\")\n",
    "                        return json.dumps(final_response, ensure_ascii=False, indent=2)\n",
    "                    except json.JSONDecodeError as e:\n",
    "                        print(f\"Agent: 提取到JSON块但解析失败: {e}\")\n",
    "                        print(f\"尝试解析的字符串:\\n{extracted_json_content}\")\n",
    "                        messages.append(response_message) # 解析失败，继续对话\n",
    "                else:\n",
    "                    # 如果没有匹配到 ```json 块，尝试直接解析整个 content\n",
    "                    try:\n",
    "                        final_response = json.loads(response_message.content)\n",
    "                        print(\"Agent: 任务完成，直接解析最终JSON文案。\")\n",
    "                        return json.dumps(final_response, ensure_ascii=False, indent=2)\n",
    "                    except json.JSONDecodeError:\n",
    "                        print(\"Agent: 生成了非JSON格式内容或非Markdown JSON块，可能还在思考或出错。\")\n",
    "                        messages.append(response_message) # 非JSON格式，继续对话\n",
    "                # --- END: 添加 JSON 提取和解析逻辑 ---\n",
    "            else:\n",
    "                print(\"Agent: 未知响应，可能需要更多交互。\")\n",
    "                break\n",
    "                \n",
    "        except Exception as e:\n",
    "            print(f\"调用 DeepSeek API 时发生错误: {e}\")\n",
    "            break\n",
    "    \n",
    "    print(\"\\n⚠️ Agent 达到最大迭代次数或未能生成最终文案。请检查Prompt或增加迭代次数。\")\n",
    "    return \"未能成功生成文案。\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "e25467a8-5241-4a11-9a59-b926395cd7cd",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "🚀 启动小红书文案生成助手，产品：智能手机，风格：活泼甜美\n",
      "\n",
      "-- Iteration 1 --\n",
      "Agent: 决定调用工具...\n",
      "Agent Action: 调用工具 'generate_emoji'，参数：{'context': '智能手机'}\n",
      "[Tool Call] 模拟生成表情符号，上下文：智能手机\n",
      "Observation: 工具返回结果：['🌿']\n",
      "-- Iteration 2 --\n",
      "[模型生成结果] ```json\n",
      "{\n",
      "  \"title\": \"这款智能手机也太香了吧！颜值与实力并存，爱了爱了💖\",\n",
      "  \"body\": \"姐妹们！最近入手了一款神仙智能手机，简直是我的心头好！✨\\n\\n🌟 颜值爆表：机身超薄，配色高级，拿在手里就是时尚单品！\\n🔥 性能炸裂：运行速度飞快，打游戏、刷剧完全不卡顿，电池续航也超给力！\\n📸 拍照神器：后置四摄，夜景模式绝了，自拍美颜自然到爆，再也不怕原相机了！\\n💡 智能体验：指纹解锁秒开，AI助手超贴心，生活工作两不误～\\n\\n用了几天完全离不开它，性价比超高，学生党也能轻松入手！🌿\\n\\n#智能手机推荐 #高颜值手机 #拍照神器 #学生党必备 #性价比之王\",\n",
      "  \"hashtags\": [\"#智能手机推荐\", \"#高颜值手机\", \"#拍照神器\", \"#学生党必备\", \"#性价比之王\"],\n",
      "  \"emojis\": [\"💖\", \"✨\", \"🌟\", \"🔥\", \"📸\"]\n",
      "}\n",
      "```\n",
      "Agent: 任务完成，成功解析最终JSON文案。\n",
      "\n",
      "--- 生成的文案 1 ---\n",
      "{\n",
      "  \"title\": \"这款智能手机也太香了吧！颜值与实力并存，爱了爱了💖\",\n",
      "  \"body\": \"姐妹们！最近入手了一款神仙智能手机，简直是我的心头好！✨\\n\\n🌟 颜值爆表：机身超薄，配色高级，拿在手里就是时尚单品！\\n🔥 性能炸裂：运行速度飞快，打游戏、刷剧完全不卡顿，电池续航也超给力！\\n📸 拍照神器：后置四摄，夜景模式绝了，自拍美颜自然到爆，再也不怕原相机了！\\n💡 智能体验：指纹解锁秒开，AI助手超贴心，生活工作两不误～\\n\\n用了几天完全离不开它，性价比超高，学生党也能轻松入手！🌿\\n\\n#智能手机推荐 #高颜值手机 #拍照神器 #学生党必备 #性价比之王\",\n",
      "  \"hashtags\": [\n",
      "    \"#智能手机推荐\",\n",
      "    \"#高颜值手机\",\n",
      "    \"#拍照神器\",\n",
      "    \"#学生党必备\",\n",
      "    \"#性价比之王\"\n",
      "  ],\n",
      "  \"emojis\": [\n",
      "    \"💖\",\n",
      "    \"✨\",\n",
      "    \"🌟\",\n",
      "    \"🔥\",\n",
      "    \"📸\"\n",
      "  ]\n",
      "}\n"
     ]
    }
   ],
   "source": [
    "# 测试案例 1: 深海蓝藻保湿面膜\n",
    "product_name_1 = \"智能手机\"\n",
    "tone_style_1 = \"活泼甜美\"\n",
    "result_1 = generate_rednote(product_name_1, tone_style_1)\n",
    "\n",
    "print(\"\\n--- 生成的文案 1 ---\")\n",
    "print(result_1)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "id": "6a3f22e8-16c2-45f1-bf2e-84b41337a8d2",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "🚀 启动小红书文案生成助手，产品：无线耳机，风格：知性温柔\n",
      "\n",
      "-- Iteration 1 --\n",
      "Agent: 决定调用工具...\n",
      "Agent Action: 调用工具 'generate_emoji'，参数：{'context': '无线耳机 知性温柔'}\n",
      "[Tool Call] 模拟生成表情符号，上下文：无线耳机 知性温柔\n",
      "Observation: 工具返回结果：['💧', '🎉']\n",
      "-- Iteration 2 --\n",
      "Agent: 决定调用工具...\n",
      "Agent Action: 调用工具 'query_product_database'，参数：{'product_name': '无线耳机'}\n",
      "[Tool Call] 模拟查询产品数据库：无线耳机\n",
      "Observation: 工具返回结果：根据提供的上下文，并未提及无线耳机的相关信息，因此无法返回相关答案。如果您需要其他产品（如平板电脑、智能手表或笔记本电脑）的详细信息，我可以为您提供帮助。\n",
      "-- Iteration 3 --\n",
      "Agent: 决定调用工具...\n",
      "Agent Action: 调用工具 'search_web'，参数：{'query': '2023年无线耳机热门卖点'}\n",
      "[Tool Call] 模拟搜索网页：2023年无线耳机热门卖点\n",
      "Observation: 工具返回结果：未找到关于 '2023年无线耳机热门卖点' 的特定信息，但市场反馈通常关注产品成分、功效和用户体验。\n",
      "\n",
      "⚠️ Agent 达到最大迭代次数或未能生成最终文案。请检查Prompt或增加迭代次数。\n",
      "\n",
      "--- 生成的文案 2 ---\n",
      "未能成功生成文案。\n"
     ]
    }
   ],
   "source": [
    "# 测试案例 2: 美白精华\n",
    "product_name_2 = \"无线耳机\"\n",
    "tone_style_2 = \"知性温柔\"\n",
    "result_2 = generate_rednote(product_name_2, tone_style_2)\n",
    "\n",
    "print(\"\\n--- 生成的文案 2 ---\")\n",
    "print(result_2)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "478ac7d1-99eb-4e23-9c5b-6e38dd017101",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "🚀 启动小红书文案生成助手，产品：平板电脑，风格：简洁、数据详实\n",
      "\n",
      "-- Iteration 1 --\n",
      "Agent: 决定调用工具...\n",
      "Agent Action: 调用工具 'query_product_database'，参数：{'product_name': '平板电脑'}\n",
      "[Tool Call] 模拟查询产品数据库：平板电脑\n"
     ]
    }
   ],
   "source": [
    "# 测试案例 2: 美白精华\n",
    "product_name_3 = \"平板电脑\"\n",
    "tone_style_3 = \"简洁、数据详实\"\n",
    "result_3 = generate_rednote(product_name_3, tone_style_3)\n",
    "\n",
    "print(\"\\n--- 生成的文案 3 ---\")\n",
    "print(result_3)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "0769200c-13b7-48f9-ba30-18a3d4b3fcb3",
   "metadata": {},
   "outputs": [],
   "source": [
    "import json\n",
    "\n",
    "def format_rednote_for_markdown(json_string: str) -> str:\n",
    "    \"\"\"\n",
    "    将 JSON 格式的小红书文案转换为 Markdown 格式，以便于阅读和发布。\n",
    "\n",
    "    Args:\n",
    "        json_string (str): 包含小红书文案的 JSON 字符串。\n",
    "                           预计格式为 {\"title\": \"...\", \"body\": \"...\", \"hashtags\": [...], \"emojis\": [...]}\n",
    "\n",
    "    Returns:\n",
    "        str: 格式化后的 Markdown 文本。\n",
    "    \"\"\"\n",
    "    try:\n",
    "        data = json.loads(json_string)\n",
    "    except json.JSONDecodeError as e:\n",
    "        return f\"错误：无法解析 JSON 字符串 - {e}\\n原始字符串：\\n{json_string}\"\n",
    "\n",
    "    title = data.get(\"title\", \"无标题\")\n",
    "    body = data.get(\"body\", \"\")\n",
    "    hashtags = data.get(\"hashtags\", [])\n",
    "    # 表情符号通常已经融入标题和正文中，这里可以选择是否单独列出\n",
    "    # emojis = data.get(\"emojis\", []) \n",
    "\n",
    "    # 构建 Markdown 文本\n",
    "    markdown_output = f\"## {title}\\n\\n\" # 标题使用二级标题\n",
    "    \n",
    "    # 正文，保留换行符\n",
    "    markdown_output += f\"{body}\\n\\n\"\n",
    "    \n",
    "    # Hashtags\n",
    "    if hashtags:\n",
    "        hashtag_string = \" \".join(hashtags) # 小红书标签通常是空格分隔\n",
    "        markdown_output += f\"{hashtag_string}\\n\"\n",
    "        \n",
    "    # 如果需要，可以单独列出表情符号，但通常它们已经包含在标题和正文中\n",
    "    # if emojis:\n",
    "    #     emoji_string = \" \".join(emojis)\n",
    "    #     markdown_output += f\"\\n使用的表情：{emoji_string}\\n\"\n",
    "        \n",
    "    return markdown_output.strip() # 去除末尾多余的空白"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "812dfe4e-d7c4-4172-a60f-36190046c126",
   "metadata": {},
   "outputs": [],
   "source": [
    "# --- 示例使用 ---\n",
    "# 假设这是 generate_rednote 函数的输出\n",
    "generated_json_output = \"\"\"\n",
    "{\n",
    "  \"title\": \"✨ 28天逆袭冷白皮！这款美白精华让我告别暗沉痘印 🌟\",\n",
    "  \"body\": \"姐妹们！我终于找到了我的本命美白精华！💖\\\\n\\\\n作为一个常年熬夜➕痘印困扰的混油皮，肤色暗沉一直是我的心头大患。直到遇见了这款美白精华，简直打开了新世界的大门！🤩\\\\n\\\\n🌟 核心成分：烟酰胺+VC衍生物，双管齐下，提亮肤色效果绝绝子！\\\\n💧 质地轻薄到爆炸，上脸秒吸收，完全不会黏腻，油皮姐妹放心冲！\\\\n🌿 用了28天，痘印肉眼可见变淡了，整张脸都透亮了起来，素颜也能打！\\\\n\\\\n使用方法也很简单：早晚洁面后，滴2-3滴在手心，轻轻按压上脸，后续再叠加保湿产品就OK啦～\\\\n\\\\n真心推荐给所有想要均匀肤色、告别暗沉的姐妹！入股不亏！💖\",\n",
    "  \"hashtags\": [\"#美白精华\", \"#提亮肤色\", \"#淡化痘印\", \"#护肤好物\", \"#冷白皮\"],\n",
    "  \"emojis\": [\"✨\", \"💖\", \"🤩\", \"💧\", \"🌿\"]\n",
    "}\n",
    "\"\"\"\n",
    "\n",
    "# 调用格式化函数\n",
    "markdown_note = format_rednote_for_markdown(generated_json_output)\n",
    "\n",
    "# 打印结果\n",
    "print(\"--- 格式化后的小红书文案 (Markdown) ---\")\n",
    "print(markdown_note)\n",
    "\n",
    "# --- 另一个例子，假设JSON解析失败 ---\n",
    "invalid_json_output = \"{'title': 'Test', 'body': 'This is not valid json'}\" # 使用单引号，非法\n",
    "markdown_error_note = format_rednote_for_markdown(invalid_json_output)\n",
    "print(\"\\n--- 格式化错误示例 ---\")\n",
    "print(markdown_error_note)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "e7feb8ea-3cae-4f33-82c3-07f05d97d951",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 调用格式化函数\n",
    "markdown_note = format_rednote_for_markdown(result_1)\n",
    "\n",
    "# 打印结果\n",
    "print(\"--- 格式化后的小红书文案 (Markdown) ---\")\n",
    "print(markdown_note)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.13.5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
